import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets,losses,layers,metrics,Sequential,optimizers

def proprocess(x,y):
    '''x is a simple image,not a batch '''
    x = tf.cast(x, dtype=tf.float32) / 255.
    y = tf.cast(y, dtype=tf.int32)

    return x,y

batchsz = 128
#[32,32,3]
(x, y), (x_val, y_val) = datasets.cifar10.load_data()
print(x.shape, y.shape, x_val.shape, y_val.shape)
y = tf.squeeze(y, axis=1)
y_val = tf.squeeze(y_val, axis=1)
y = tf.one_hot(y, depth=10)
y_val = tf.one_hot(y_val, depth=10)
print(x.shape, y.shape, x_val.shape, y_val.shape)

train_db = tf.data.Dataset.from_tensor_slices((x, y))
test_db = tf.data.Dataset.from_tensor_slices((x_val, y_val))
train_db = train_db.map(proprocess).shuffle(10000).batch(batchsz)
test_db = test_db.map(proprocess).batch(batchsz)

sample = next(iter(train_db))
print(sample[0].shape, sample[1].shape)

class MyDense(layers.Layer):
    def __init__(self, input_dim, output_dim):
        super(MyDense, self).__init__()

        self.kernel = self.add_weight('w', [input_dim, output_dim])
        #self.bias = self.add_weight('b', [output_dim])

    def call(self, inputs, training=None):

        out = inputs @ self.kernel

        return out

class MyNetWork(keras.Model):

    def __init__(self):
        super(MyNetWork, self).__init__()

        self.fc1 = MyDense(32*32*3, 256)
        self.fc2 = MyDense(256, 128)
        self.fc3 = MyDense(128, 64)
        self.fc4 = MyDense(64, 32)
        self.fc5 = MyDense(32, 10)



    def call(self, inputs, training=None):
        '''

        :param inputs:
        :param training:
        :return:
        '''
        x = tf.reshape(inputs, [-1, 32*32*3])
        #[b, 32*32*3] => [b, 256]
        x = self.fc1(x)
        x = tf.nn.relu(x)
        #[b,256] => [b, 128]
        x = self.fc2(x)
        x = tf.nn.relu(x)
        # [b,128] => [b, 64]
        x = self.fc3(x)
        x = tf.nn.relu(x)
        # [b,64] => [b, 32]
        x = self.fc4(x)
        x = tf.nn.relu(x)
        # [b,32] => [b, 10]
        logits = self.fc5(x)

        return logits

network = MyNetWork()

network.compile(
    optimizer=optimizers.Adam(lr=1e-3),
    loss=tf.losses.CategoricalCrossentropy(from_logits=True),
    metrics=['accuracy']
)
network.fit(train_db, epochs=5, validation_data=test_db, validation_freq=1)

network.evaluate(test_db)

network.save_weights('ckpt/weights.ckpt')

del network
print('saved weight')


network = MyNetWork()

network.compile(
    optimizer=optimizers.Adam(lr=1e-3),
    loss=tf.losses.CategoricalCrossentropy(from_logits=True),
    metrics=['accuracy']
)
network.load_weights('ckpt/weights.ckpt')

print('load weights from file')





